﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections;
using RemoteBase;
using BL.Service;
using BL;
using BL.Entity;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using ClassLibrary1;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
namespace LTO
{
    /// <summary>
    /// Interaction logic for MessageViewer.xaml
    /// </summary>

    public partial class MessageViewer2 : Window
    {
        internal SampleObject remoteObj;
        internal int key = 0;
        internal string yourName;
        ArrayList alOnlineUser = new ArrayList();
        tbl_NumberServer service = new tbl_NumberServer();
        List<NumberDTO> dbNUmber;
        List<string> USBList;
        string fileNameExport = "ExportData.xml";

        public MessageViewer2()
        {
            InitializeComponent();

            System.Threading.Thread sv = new System.Threading.Thread(LoadMessage);
            sv.Start();


        }

        public void SendMessage(string message)
        {
            if (remoteObj != null && message.Trim().Length > 0)
            {
                remoteObj.SendMsgToSvr(yourName + ": " + message);

            }
        }
        private void LoadMessage()
        {

            do
            {
                if (remoteObj != null)
                {

                    try
                    {


                        string tempStr = remoteObj.GetMsgFromSvr(key);
                        ArrayList onlineUser = remoteObj.GetOnlineUser();
                        if (tempStr.Trim().Length > 0)
                        {
                            key++;
                            listBox1.UpdateControlSafe(new Action(() => listBox1.Items.Insert(0, string.Format(tempStr))));
                        }


                        // bool isHaveUser = (from u in onlineUser.OfType<string>().ToList() where u == Gobalsource.UserNameLogin select u).ToList().Count > 1;
                        //if (!isHaveUser)
                        // {

                        int userCount = 0;
                        listUser.UpdateControlSafe(new Action(() => listUser.Items.Clear()));
                        string userName = string.Empty;
                        foreach (var userLogin in onlineUser)
                        {

                            User userLoginInSystem = new tbl_UserService().GetUser(userLogin.ToString());
                            if (userLoginInSystem != null && userLoginInSystem.Active)
                            {
                                userCount += 1;
                                userName += userLoginInSystem.UserName + Environment.NewLine;
                            }
                            else
                            {
                                Gobalsource.objChatWin.remoteObj.LeaveChatRoom(userLogin.ToString());
                            }

                        }
                        Gobalsource.TotalClient = userCount;
                        string updateTime = string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now);
                        lblUpdateTime.UpdateControlSafe(new Action(() => lblUpdateTime.Content = updateTime));
                        lblCountClient.UpdateControlSafe(new Action(() => lblCountClient.Content = userCount.ToString()));
                        listUser.UpdateControlSafe(new Action(() => listUser.Items.Add(userName)));
                        // }
                        // else
                        // {
                        //    Gobalsource.IsAppRunning = false;
                        //   break;
                        // }
                        // }



                    }
                    catch (Exception)
                    {
                        Gobalsource.IsAppRunning = false;
                        break;
                    }
                }
                System.Threading.Thread.Sleep(1000);
            } while (Gobalsource.IsAppRunning);

            MessageBox.Show("Message View Server is Close");
            this.Dispatcher.Invoke((Action)(() =>
            {
                Gobalsource.objChatWin.SendMessage("ออกจากระบบ");
                if (Gobalsource.UserNameLogin != null)
                    Gobalsource.objChatWin.remoteObj.LeaveChatRoom(Gobalsource.UserNameLogin);
                if (Gobalsource.chan != null)
                    ChannelServices.UnregisterChannel(Gobalsource.chan);
                Application.Current.Shutdown();
            }));
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // _messageBackens.SendMessage("เข้าสู่ระบบ");

        }

        private void ClearTbl_Click(object sender, RoutedEventArgs e)
        {
            tbl_NumberServer objTblNum = new tbl_NumberServer();
            objTblNum.ClearTable();
            Gobalsource.objChatWin.SendMessage("ล้างข้อมูล");
            MessageBox.Show("ล้างข้อมูลเรียบร้อย", "Clear data complate", MessageBoxButton.OK, MessageBoxImage.Information);

        }
        private void textBoxEntryField_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return || e.Key == Key.Enter)
            {


            }
        }
        private void btnShutdown_Click(object sender, RoutedEventArgs e)
        {

            Gobalsource.IsAppRunning = false;
            //Application.Current.Shutdown();
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            USBList = new Class1().GetUSB();
            if (USBList != null && USBList.Count > 0)
            {
                dbNUmber = new List<NumberDTO>();
                dbNUmber = service.getAllnumber(false);
                string xmlObj = GetXMLFromObject(dbNUmber);

                string filename = string.Format(@"{0}\{1}", USBList[0], fileNameExport);
                string folder = string.Empty;
                string[] splitFolder = filename.Split('\\');
                for (int i = 0; i < splitFolder.Length - 1; i++)
                {
                    folder += splitFolder[i] + "\\";
                }
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                if (!File.Exists(filename))
                {
                    var cFile = File.Create(filename);
                    cFile.Close();
                }
                
                File.WriteAllText(filename, xmlObj);
                MenuItem mItem = (MenuItem)sender;
                string message = mItem.Header.ToString();
                message = message.Substring(message.IndexOf('>')+1, message.Length - (message.IndexOf('>')+1));
                Gobalsource.objChatWin.SendMessage(message.Trim());
                MessageBox.Show(string.Format("ส่งออกไฟล์เรียบร้อย {0} ", filename), "Export Information", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("กรุณาใส่ USB", "Export Information", MessageBoxButton.OK, MessageBoxImage.Error);

            }
        }

        private string getExportImportPath()
        {
            string path = string.Empty;
            if (USBList != null && USBList.Count > 0)
            {
                foreach (string UsbDrive in USBList)
                {
                    path = string.Format(@"{0}\{1}", UsbDrive, fileNameExport);
                    if (File.Exists(path))
                    {
                        break;
                    }
                }
            }
            return path;
        }
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                USBList = new Class1().GetUSB();
                List<NumberDTO> ReadNUmber = new List<NumberDTO>();

                string filename = getExportImportPath();

                string line = "";
                string resultXML = "";
                StreamReader sr = File.OpenText(filename);
                while ((line = sr.ReadLine()) != null)
                {
                    resultXML += line;
                }
                ReadNUmber = FromXml<List<NumberDTO>>(resultXML);
                dbNUmber = ReadNUmber;
                MenuItem mItem = (MenuItem)sender;
                string message = mItem.Header.ToString();
                message = message.Substring(message.IndexOf('>') + 1, message.Length - (message.IndexOf('>') + 1));
                Gobalsource.objChatWin.SendMessage(message.Trim());
                mItem.Header = string.Format("<R>     อ่านข้อมูลจาก Flash Drive({0} รายการ)", dbNUmber.Count);
                MessageBox.Show("อ่านไฟล์เรียบร้อย ", "ReadFile Information", MessageBoxButton.OK, MessageBoxImage.Information);


                //}
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "Error Open File", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            if (dbNUmber != null && dbNUmber.Count > 0)
            {
                int result = 0;
                result = service.ImportFile(dbNUmber, Gobalsource.UserNameLogin);
                dbNUmber = new List<NumberDTO>();

                MenuItem mReadFlashDrice = (MenuItem)sender;
                string message = mReadFlashDrice.Header.ToString();
                message = message.Substring(message.IndexOf('>') + 1, message.Length - (message.IndexOf('>') + 1));
                Gobalsource.objChatWin.SendMessage(message.Trim());

                mReadFlashDrice.Header = "<R>     อ่านข้อมูลจาก Flash Drive";

                MessageBox.Show(string.Format("นำเข้าไฟล์ เรียบร้อย {0} Record", result), "Import Information", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("กรุณา อ่านข้อมูลจาก Flash Drive ก่อน, result", "Error Open File", MessageBoxButton.OK, MessageBoxImage.Error);

            }
        }

        public string GetXMLFromObject(object o)
        {
            XmlSerializer XmlS = new XmlSerializer(o.GetType());

            StringWriter sw = new StringWriter();
            XmlTextWriter tw = new XmlTextWriter(sw);



            XmlS.Serialize(tw, o);
            return sw.ToString();
        }
        protected T FromXml<T>(String xml)
        {
            T returnedXmlClass = default(T);

            try
            {
                using (TextReader reader = new StringReader(xml))
                {
                    try
                    {
                        returnedXmlClass = (T)new XmlSerializer(typeof(T)).Deserialize(reader);
                    }
                    catch (InvalidOperationException)
                    {
                        // String passed is not XML, simply return defaultXmlClass
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return returnedXmlClass;
        }

        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            new UserSetup().Show();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() =>
            {
                Gobalsource.IsAppRunning = false;
            }));
        }






    }
}
